package user

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/shiwjlinux/vblog01/common"
	"golang.org/x/crypto/bcrypt"
)

func NewMeta() *Meta {
	return &Meta{
		CreatedAt: time.Now().Unix(),
	}
}

type Meta struct {
	Id        int   `json:"id"`
	CreatedAt int64 `json:"created_at"`
	UpdatedAt int64 `json:"updated_at"`
}

func NewUser(req *CreateUserRequest) *User {
	return &User{
		Meta:              common.NewMeta(),
		CreateUserRequest: req,
	}
}

type User struct {
	*common.Meta
	*CreateUserRequest
}

func (u *User) MaskPassword() {
	u.Password = "******"
}

func (u *User) TableName() string {
	return AppName + "s"
}

func (req *User) String() string {
	b, _ := json.MarshalIndent(req, "", " ")
	return string(b)
}

func NewCreateUserRequest() *CreateUserRequest {
	return &CreateUserRequest{
		Role:  ROLE_VISITOR,
		Label: make(map[string]string),
	}
}

type CreateUserRequest struct {
	Username string            `json:"username" validate:"required"`
	Password string            `json:"password" validate:"required"`
	Role     Role              `json:"role"`
	Label    map[string]string `json:"label" gorm:"column:label;serializer:json"`
}

func (req *CreateUserRequest) Validate() error {
	if req.Username == "" {
		return fmt.Errorf("用户名不能为空")
	}
	return nil
}

func (req *CreateUserRequest) HashPassword() error {
	bcryptBytes, err := bcrypt.GenerateFromPassword([]byte(req.Password),
		bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	req.Password = string(bcryptBytes)
	return nil
}

func (req *CreateUserRequest) CheckPassword(password string) error {
	return bcrypt.CompareHashAndPassword([]byte(req.Password), []byte(password))
}

func NewUserSet() *UserSet {
	return &UserSet{
		Items: []*User{},
	}
}

type UserSet struct {
	Total int64
	Items []*User
}
